package com.atguigu.gulimall.auth.controller;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.service.LoginService;
import com.atguigu.gulimall.auth.service.RegisterService;
import com.atguigu.gulimall.auth.vo.LoginVo;
import com.atguigu.gulimall.auth.vo.RegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.Objects;


/**
 * @DESCRIPTION: 登录控制器
 * @author: zr
 * @DATE: 2022/12/29 21:30
 */
@Controller
public class LoginController {

    @Autowired
    private RegisterService registerService;
    @Autowired
    private LoginService loginService;

    @GetMapping({"/sms/sendCode/{phone:.+}","/sms/sendCode/"})
    @ResponseBody
    public R sendCode( @PathVariable(value = "phone",required = false)String phone) {
        return loginService.sendCode(phone);
    }

    @PostMapping("/register")
    public String register(@Validated RegisterVo registerVo, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        return registerService.register(registerVo, bindingResult, redirectAttributes);
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        // 判断当前用户是否已经登录
        Object loginUser = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (Objects.isNull(loginUser)) {
            // 用户未登录 跳转到登录页面
            return "login";
        } else {
            // 重定向到首页
            return "redirect:http://gulimall.com";
        }
    }

    @PostMapping("/login")
    public String login(LoginVo loginVo, HttpSession session, RedirectAttributes redirectAttributes) {
        return loginService.login(loginVo, session, redirectAttributes);
    }
}
